﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using GeneticAlgorythm.Algorythm;

namespace GeneticAlgorythm.Utils
{
    public class PopulationFileSaver : PopulationSaver
    {
        private string filePath;

        public PopulationFileSaver(string filePath)
        {
            this.filePath = filePath;
        }

        public void save(Population population)
        {
            File.Delete(filePath);
            File.AppendAllText(filePath, population.ToString());
        }

        public void load(Population population)
        {
            List<string> fileLines = File.ReadLines(filePath).ToList();
            foreach(string line in fileLines){
                population.add(lineToIndividual(line));
            }
        }

        private Individual lineToIndividual(string line)
        {
            string[] genesString = line.Split(',');
            List<int> genesInt = new List<int>();

            foreach (string gene in genesString)
            {
                if(!gene.Equals(""))
                    genesInt.Add(Convert.ToInt32(gene));
            }
            return new Individual(new PermutationChromosome(genesInt));
        }
    }
}
